338. 比特位计数
为保证权益,题目请参考 338. 比特位计数(From LeetCode).
解决方案1
Python
python
"""
题目:338. 比特位计数
https://leetcode-cn.com/problems/counting-bits/
https://leetcode-cn.com/problems/counting-bits/
https://leetcode-cn.com/problems/counting-bits/
"""
from typing import List
class Solution:
def countBits(self, num: int) -> List[int]:
if num == 0:
return [0]
elif num == 1:
return [0,1]
ans = [0 for _ in range(num+1)]
ans[0] = 0
ans[1] = 1
offset = 2
for i in range(2, num+1, 1):
if i - offset == offset:
offset = i
ans[i] = ans[i-offset] + 1
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32